import '@/pages/components/StyleFile/btnStyle.less';
import { CellsMetaUpdateCPASTableData, extractFileInfo, Md5_16 } from '@/utils';
import { Button } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import ChangeTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/ChangeTemplatePopup';
import SaveTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/SaveTemplatePopup';
import CpasTableFs, { ImportToTitle } from '~/public/cpas-business/cpas-table/CpasTableFs';
import Details from '~/public/cpas-business/cpas-table/ExcelGrid/components/Validator/CheckDetails';
import { CpasIcon } from '~/public/cpas-ui';
import './index.less';
import {
  batchClearData,
  batchClearGSData,
  batchVerifyRecal,
  getColumnsMapByReport,
  getCpasAllTids,
  getCpasByCategory,
  getPeriodInfo,
  getRowsMapByReport,
  gettableIsVerifyTid,
  getTableperiodAndPointList,
  getVerifyByRMap,
  queryVerifyStatefs,
  reloadBatchDataRecalculateFs,
  saveTemplateApi,
  templateInitApi,
} from './service';
// import { UpdateCpasTableDataZero, UpdateCPASTableData } from '~/public/cpas-ui/components-ui/components/ExcelGrid/Tools/index';
import CpasTableChangePupop from '../../components/CpasTableChangePupop';
// import { Upload } from "antd";, { Item as ButtonItem }
import axios from 'axios';
import DropDownButton from 'devextreme-react/drop-down-button';
import SettingFormPupop from './settingFormPupop';
import SettingFormPupopHB from './settingFormPupopHB';

import { getSeekAuditReportTemplate } from '@/pages/reportBuilder/service';
import CpasModal from '~/public/cpas-business/cpas-table/CpasModal';
import ImportExcelModal from '~/public/cpas-business/cpas-table/CpasModal/ImportExcelModal';
import PageLoading from "../../components/PageLoading";
import PopupComponents from '../../components/PopupComponents';
import { saveTemplate,getTemplate } from '@/services/cpasRequest';



const CommonCpasTable = React.forwardRef((props: any, ref: any) => {
  const {
    CPASTableProps,
    tableNameGroup,
    excelParams,
    antTabsTabPaneDetail2,
    cpasChangeSpinAntTabs,
    commonCpasTableDisplay,
    isInitBtn,
    changeIsInitBtn,
    CPASTableTabName,
    biaoAllData,
  } = props;

  const { CPASTableType, WscwbbType, tableName, titleName, origin, tabsIndex } = CPASTableProps;
  const { initialState } = useModel('@@initialState');
  const { cpasTableZeroReplace, negationRow } = initialState?.settings;
  const { dbname, bsdw, zcbfid, zcbfName } = initialState?.curPart as API.CurPart;
  const [rowsMapList, setRowsMapList] = useState<any[]>([]);
  const [columnsMapList, setColumnsMapList] = useState<any[]>([]);
  const cpasTableFsRef = useRef<any>(null);
  const saveTemplatePopupRef = useRef<any>();
  const changeTemplatePopupRef = useRef<any>();
  const [showMenuToolBar, setShowMenuToolBar] = useState<boolean>(false);
  const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const [serverDataLen, setServerDataLen] = useState<number>(2);
  const cpasTableChangePupopRef = useRef<any>(null);
  const [openDetails, setOpenDetails] = useState<boolean>(false);
  // const [visiblePopup, setVisiblePopup] = useState<boolean>(false);
  const refSettingFormPupop = useRef<any>(null);
  const refSettingFormPupopHB = useRef<any>(null);
  const [visibleSetting, setVisibleSetting] = useState<boolean>(false);
  const [visibleSettingHB, setVisibleSettingHB] = useState<boolean>(false);

  const visiblePopupRef = useRef<any>(''); // tid
  const cpasTableTid = useRef<any>(''); // tid
  const devDataRef = useRef<any>(''); // tid
  const refsForm = useRef<any>();
  const [formAllData, setFormAllData] = useState<any>({ pupupTitleText: '' });
  const [cpasTid, setCpasTid] = useState<string>("");
  const cpasTableAllRowsMapsData = useRef<any[]>([]); //
  const [titleRightText, setTitleRightText] = useState<string>(' ');
  const [titleLeftText, setTitleLeftText] = useState<string>(' ');
  const [titleCenterText, setTitleCenterText] = useState<string>('');

  const [titleYearStr, setTitleYearStr] = useState<string>(' ');
  const [popupDevData, setPopupDevData] = useState<any>([]);
  const [commonCpasTableNot, setCommonCpasTableNot] = useState<string>(' ');

  const [titleYearExport, setTitleYearExport] = useState<string>(' ');
  const [titleYearExportMin, setTitleYearExportMin] = useState<string>(' ');
  const PopupComponentsRef = useRef<any>(null);
  const [loadingContent, setLoadingContent] = useState<string>('加载中...');

  // const [pupupTitleText, setPupupTitleText] = useState<string>('单位：人民币元');

  // const [verifyResult, setVerifyResult] = useState<any[]>([]);

  const [resultListData, setResultListData] = useState<any>({
    verifyResult: [],
    isBackAll: false,
  });
  const importExcelRef = useRef<any>(null);
  const exportExcelRef = useRef<any>(null);

  //注意mapList接收的映射源为数组结构(handson所决定) [,,,]
  function dataObjToArray(objData: any[]) {
    const result = [''];
    objData.forEach((item) => {
      result.push(item.value);
    });
    return result;
  }

  //初始化表格映射数据源
  async function loadRowsMapData() {
    const rowsMapListData = await getRowsMapByReport({ dbname });
    setRowsMapList(dataObjToArray(rowsMapListData.data));
  }
  async function loadColumnsMapData() {
    const columnsMapListData = await getColumnsMapByReport({ dbname });
    setColumnsMapList(dataObjToArray(columnsMapListData.data));
  }
  // 获取真是的CPASTable的ref
  const getRealCPASTableRef = () => {
    if (cpasTableFsRef.current) {
      const realHandSonGridRef = cpasTableFsRef.current.handsonTableFs.current;
      return realHandSonGridRef;
    }
    return null;
  };
  const fetchTablePeriodList = async () => {
    // setSpinLoad(true);
    // setLoadingContent('获取年度中...');
    const isPoint = tabsIndex < 3 || tableName === '审定财务-资产减值准备情况表' ? 0 : 1;
    console.log(tabsIndex, isPoint, '@@@');
    let cpasTableTitleList: string[] = [];
    let cpasTableCmapList: any[] = [];
    const resYear = await getPeriodInfo({ dbname });
    if (resYear.success) {
      const resSetting = await getTableperiodAndPointList({
        dbname,
        isDesc: true,
        reportType: isPoint,
      });
      console.log("🚀 ~ fetchTablePeriodList ~ resSetting:", resSetting)
      if (resSetting.success) {
        if (resYear.data.yearCnt > 1) {
          setTitleYearStr(' ');
          setTitleYearExport(' ');
          setTitleYearExportMin(' ');
          setCommonCpasTableNot('commonCpasTableNotTitle');
          window.localStorage.setItem(`${origin}_${dbname}`, JSON.stringify({}));
        } else {
          let yearStrTitle = ' ';
          let ndYear = ' ';
          let yearStr = ' ';
          if (resSetting.data?.length) {
            if (isPoint === 0) {
              const resList = await getTableperiodAndPointList({
                dbname,
                isDesc: true,
                reportType: 1,
              });
              const eeee = resList.data.sort((a: any, b: any) => b.id - a.id);
              const aaa = eeee[0].reportDate;
              const bbb = resSetting.data[0].reportDate;
              yearStr = bbb;
              yearStrTitle = bbb;
              ndYear = aaa;
              const titleDateObj = { ndYear, yearStr };
              // // 本地存储 持久化数据
              window.localStorage.setItem(`${origin}_${dbname}`, JSON.stringify(titleDateObj));
            } else {
              const getTitleDateObj: any = window.localStorage.getItem(`${origin}_${dbname}`);
              const eeee = resSetting.data.sort((a: any, b: any) => b.id - a.id);
              yearStrTitle = eeee[0].reportDate;
              ndYear = eeee[0].reportDate;
              yearStr = JSON.parse(getTitleDateObj)?.yearStr ?? ' ';
            }
          } else {
            notify(`4获取批量设置的日期报错！`, 'error', 2000);
          }
          setTitleYearExportMin(yearStr);
          setTitleYearExport(ndYear);
          setTitleYearStr(yearStrTitle);
          setCommonCpasTableNot(' ');
        }
        if (resSetting.data?.length) {
          cpasTableTitleList = resSetting.data.map((item: { title: string }) => {
            return item.title;
          });
          cpasTableCmapList = resSetting.data.map((item: { data_id: any; fieldName: string }) => {
            return {
              year_id: item.data_id,
              year_fieldName: item.fieldName,
            };
          });
          console.log(cpasTableTitleList, cpasTableCmapList, '@@@');
          return { data: cpasTableCmapList, dataTitle: cpasTableTitleList, success: true };
        }
        // setSpinLoad(false);
        // setLoadingContent(' ');
        return { data: [], dataTitle: [], success: false };
      } else {
        notify(`获取批量设置的数据列表失败！`, 'error', 2000);
        // setSpinLoad(false);
        // setLoadingContent(' ');
        return { data: [], dataTitle: [], success: false };
      }
    } else {
      notify(`获取首页年度列表失败！`, 'error', 2000);
      // setSpinLoad(false);
      // setLoadingContent(' ');
    }
    return { data: [], dataTitle: [], success: false };
  };

  // 业务要加那个预制校验
  const changeCrticulationVerify = async (dataRef: any) => {
    const verifyResult = dataRef.articulationVerifyService.artParseResultList;
    const formulaList = dataRef.articulationVerifyService.artVerifyFormulaList;
    const parseList = await dataRef.articulationVerifyService.parseArtVerifyFormula(formulaList);
    // 增加 单点标志值 默认 []
    const resultItem = dataRef.articulationVerifyService?.artResultItem;
    if (!resultItem) return;
    if (resultItem?.length > 0) {
      dataRef.articulationVerifyService.markBeVerifiedItem(resultItem[0], true, true);
    } else if (verifyResult.length > 0) {
      dataRef.articulationVerifyService.batchMarkBeVerifiedItem(parseList);
    }
  };

  const loadTableByServerData = async (serverName: string) => {
    setSpinLoad(true);
    setLoadingContent('加载中...');
    let serverData: any;
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      console.log('@@@ 获取真是的CPASTable的ref', realrealHandSonGridRefRef);
      try {
        serverData = await realrealHandSonGridRefRef.loadTableByServer(serverName);
        console.log('--------serverData初始数据 @@@', serverData);
        if (serverData.data) {
          const res = await gettableIsVerifyTid({
            tableName,
            dbname,
            isTid: true,
          });
          if (res.success && res.data?.length) {
            const tid = res.data[0].tid;
            cpasTableTid.current = res.data[0].tid;
            setCpasTid(res.data[0].tid);
            // debugger;
            console.log(`@@@  ${serverName}`, cpasTableTid.current);
            const verifyData = await realrealHandSonGridRefRef.loadVerifyByServer(tid);
            const fsParams = {
              dbname,
              tid: tid,
              type: 'fs',
            };
            const lodaTableZl = await queryVerifyStatefs(fsParams);
            if (lodaTableZl.code === 200) {
              realrealHandSonGridRefRef.setVerifyData(verifyData);
              console.log(verifyData.artParseResultList, '@@@ verifyData.artParseResultList');
              // setVerifyResult(verifyData.artParseResultList);
              setResultListData({
                verifyResult: verifyData.artParseResultList,
                isBackAll: false,
              });
            }
          } else {
            notify(`获取tid失败！`, 'error', 2000);
          }
          await realrealHandSonGridRefRef.reloadTable(serverData, 'fs', null, true);
          await changeCrticulationVerify(realrealHandSonGridRefRef);
          setServerDataLen(serverData.data.length);
          await antTabsTabPaneDetail2();
          setSpinLoad(false);
          setLoadingContent(' ');
          console.log('   数据@@@ tid', origin);
          notify(`获取该表数据成功！`, 'success', 2000);
          return {
            data: serverData,
            msg: serverData.msg,
            success: true,
          };
        } else {
          setServerDataLen(2);
          notify(`获取数据失败：${serverData.msg}！`, 'warning', 2000);
          setSpinLoad(false);
          setLoadingContent(' ');
          realrealHandSonGridRefRef.resetTable('fs');
          return {
            data: [],
            msg: serverData.msg,
            success: false,
          };
        }
      } catch (e) {
        setServerDataLen(2);
        notify(`没有该表:【${serverName}】的数据！`, 'warning', 2000);
        setSpinLoad(false);
        setLoadingContent(' ');
        realrealHandSonGridRefRef.resetTable('fs');
        return {
          data: [],
          msg: `没有该表:【${serverName}】的数据！`,
          success: false,
        };
      }
    }
    return;
  };
  const batchVerifyRecalFun = async (isAudio: boolean, rundata?: string) => {
    // let allTidData: any[] = [];
    let loadingText = '';
    let batchParams: any = {}
    if (isAudio) {
      // allTidData = [cpasTableTid.current];
      batchParams = {
        dbname,
        data_id: '',
        tids: [cpasTableTid.current],
        cpasTableType: 'fs',
      }
      loadingText = '正在勾稽重算...';
    } else {
      loadingText = '正在批量勾稽重算...';
      const resTidData = await getallTidsList(true);
      if (resTidData.resTid?.length) {
        // allTidData = resTidData.resTid;
        batchParams = {
          dbname,
          data_id: '',
          tids: resTidData.resTid,
          cpasTableType: 'fs',
          bsInfo: {
            bsType: origin === '审定财务' ? "sd" : "ws",
            isAll: true
          }
        }
      }
    }
    setSpinLoad(true);
    setLoadingContent(loadingText);
    const res: any = await batchVerifyRecal(batchParams);
    if (res.success) {
      if (res.data.errorTotal === 0) {
        notify(`${loadingText},成功！`, 'success', 2000);
      } else {
        const reName = res.data.processError.map((item: any) => item.name).join(';');
        notify(`【${reName}】，勾稽重算失败。`, 'warning', 4000);
      }
      antTabsTabPaneDetail2();
      await loadTableByServerData(rundata || tableName);
      console.log('aaa111')
    } else {
      notify(`${loadingText},失败！`, 'error', 4000);
    }
    setSpinLoad(false);
    setLoadingContent(' ');
  };

  const cpasTableReloadBatch = async (isAudio: boolean, data_idCan: string = '') => {
    if (isAudio && tabsIndex > 5) {
      await fetchTablePeriodList();
      setSpinLoad(false);
      setLoadingContent(' ');
      return;
    }
    const tempAllData = [...biaoAllData];
    let allParameters: any = {
      sqlApiName: 'account.ws.wscwbb',
      origin,
      actionCol: origin === '审定财务' ? 3 : 2,
      paramsData: [],
    };
    tempAllData.forEach((item: any, index: number) => {
      if (index > 4) return;
      if (isAudio) {
        if (item.propsData.tableName === tableName) {
          allParameters.paramsData.push(item.propsData);
        }
      } else {
        allParameters.paramsData.push(item.propsData);
      }
    });
    try {
      setSpinLoad(true);
      setLoadingContent('数据刷新中...');
      if (isAudio) {
        allParameters = {
          ...allParameters,
          currentTableIndex: tabsIndex - 1,
        };
      }
      const paramBatch: any = {
        dbname,
        allParameters,
        negationRow,
        data_id: data_idCan,
      };

      const res: any = await reloadBatchDataRecalculateFs(paramBatch);
      if (res.success) {
        if (res.data.errorTotal === 0) {
          notify('批量刷新成功！', 'success', 2000);
        } else {
          const reName = res.data.processError.map((item: any) => item.name).join(';');
          notify(`【${reName}】，刷新失败。`, 'warning', 4000);
        }
        const resYear = await fetchTablePeriodList();
        if (resYear.success) {
          await batchVerifyRecalFun(isAudio);
        }
        setSpinLoad(false);
        setLoadingContent(' ');
      } else {
        setSpinLoad(false);
        setLoadingContent(' ');
        notify(`【${res.msg}】，刷新失败。`, 'warning', 4000);
      }
    } catch (error) {
      setSpinLoad(false);
      setLoadingContent(' ');
      notify('刷新失败！', 'warning', 2000);
    }
  };

  /**
   * cpas表格数据存储到线上
   */
  const saveToServer = async () => {
    const realHandSonGridRef = getRealCPASTableRef();
    if (realHandSonGridRef) {
      try {
        const Md5_16Str = Md5_16(tableName);
        await changeCrticulationVerify(realHandSonGridRef);
        const res = await realHandSonGridRef.saveToServer(tableName, CPASTableType, Md5_16Str); 
        if (res) { 
          const serverData = await realHandSonGridRef.loadTableByServer(tableName); 
          console.log("🚀 ~ saveToServer ~ serverData:", serverData)
 
          getTemplate(bsdw).then((ress) => {
            if(ress.data){
              saveTemplate({
                bsdwxydm:ress.data.bsdwxydm,
                mergeType: 2,
                reporttype: CPASTableTabName,
                reportinfo: JSON.stringify(serverData), 
              }) 
            } 
          }) 
          
          await realHandSonGridRef.reloadTable(serverData, 'fs', null, true);
          const dataGrid = realHandSonGridRef.getCpasTableGrid();
          setServerDataLen(dataGrid.data.length);
          notify(`保存成功！`, 'success', 2000);
          await antTabsTabPaneDetail2();
          return true;
        }
        return false;
      } catch (error) {
        notify(`保存失败！`, 'error', 2000);
        return false;
      }
    }
    return false;
  };

  // 保存并刷新
  const saveAndReload = async () => {
    const resSave = await saveToServer();
    if (resSave) {
      cpasTableReloadBatch(true);
    }
  };
  const getallTidsList = async (isaaaa: boolean = false) => {
    const res = await getCpasAllTids({
      dbname,
      originTableName: `${origin}-`,
      isAllTid: isaaaa,
    });
    console.log(res, '@@@ CpasAllTids');
    if (res.success) {
      const resMap = res.data.map((item: any) => item?.tid).filter((item: any) => item);
      return {
        resTid: resMap,
        resData: res.data,
      };
    } else {
      notify('获取AllTids列表失败!', 'error', 2000);
    }
    return {
      resTid: [],
      resData: [],
    };
  };

  //  导入带标题头的xlsx
  const importChange = (file: any, self: any) => {
    ImportToTitle(file, self);
  };

  const exportExcel = async (isAll: boolean) => {
    // console.log('@@@', excelParamsData);
    // let tempSignData: any[] = await getDevDataList();
    const tempExcelDataArr: any = [...excelParams];
    if (origin === '审定财务') {
      const getIsAddObj: any = window.localStorage.getItem(`审定财务-资产减值准备情况表-${dbname}`);
      const isLocalAdd = JSON.parse(getIsAddObj)?.isADD ?? false;
      if (isLocalAdd) {
        tempExcelDataArr.push({
          cpastableParam: {
            tname: '审定财务-资产减值准备情况表',
            data_id: '',
            type: 'fs',
          },
          // excelSheetName: "资产减值准备情况表",
          // tableTitle: "资产减值准备情况表",
          tableDate: ' ',
          // tableLfDesc: `编制单位： ${bsdw}`,
          // tableRiDesc: "单位：人民币元",
          isExportTableTitle: true,
          exportType: 'primary',
          // isColumnNum: true,: true,
          isBatchExport: true,
        });
      }
    }
    const tempExcelData = tempExcelDataArr.map((itemParam: any, index: number) => {
      if (titleYearStr) {
        itemParam.tableDate =
          index < 2 || itemParam.cpastableParam.tname === '审定财务-资产减值准备情况表'
            ? titleYearExportMin
            : titleYearExport;
      } else {
        itemParam.tableDate = ' ';
      }
      if (index < 5) {
        itemParam.signDirection = 'vertical';
      } else {
        itemParam.signDirection = 'horizontal';
      }
      return itemParam;
    });
    let xlsxName = ' ';
    if (isAll) {
      if (origin === '审定财务') {
        xlsxName = '审定财务报表';
      } else {
        xlsxName = '未审财务报表';
      }
    } else {
      if (origin === '审定财务') {
        xlsxName = `审定财务报表-${CPASTableTabName}`;
      } else {
        xlsxName = `未审财务报表-${CPASTableTabName}`;
      }
    }

    // console.log(tempExcelData, '@@@');
    // 1、单个导出文件名称：未审财务报表+功能页签名，审定财务报表+功能页签名，试算平衡表：年度—试算平衡表—页签名—期初/期末；
    // 2、批量导出：未审财务报表、审定财务报表、年度—试算平衡表；
    const dialog_result = await window.electronComponents.showSaveDialog(
      'xlsx',
      `${xlsxName}.xlsx`,
    );
    if (!dialog_result.canceled) {
      let radioTable: any = [];
      if (isAll) {
        radioTable = tempExcelData.filter((item: any) => {
          return item.isBatchExport;
        });
      } else {
        radioTable = tempExcelData.filter((item: any) => {
          return item.cpastableParam.tname === tableName;
        });
      }
      // console.log(tempExcelData, radioTable, tableName, '@@@');
      const fileData = extractFileInfo(dialog_result.filePath);
      const params = {
        excelInfo: radioTable,
        dbname,
        directoryPath: fileData.dirName,
        excelFileName: fileData.fileName,
        projectName: bsdw,
      };
      const url = `/cpasApi/cpasTableEngine/getCpatableToBatchExportExcel`;
      const data = await axios.post(url, params);
      if (data.data?.data?.code) {
        return {
          code: data.data.data.code,
          msg: data.data.data.msg,
          ok: data.data.data.ok,
          type: '导出',
        };
      }
      const tempMsg = 'EBUSY: resource busy or locked, open';
      const isTrue = data.data.msg.includes(tempMsg);
      if (isTrue) {
        return {
          code: data.data.code,
          msg: '文件已被程序打开，需要关闭已被打开的文件。',
          ok: data.data.ok,
          type: '导出',
        };
      }
      return {
        code: data.data.code,
        msg: data.data.msg,
        ok: data.data.data,
        type: '导出',
      };
    }
    return {
      code: 404,
      msg: '取消了选择路径！',
      ok: false,
      type: '取消',
    };
  };
  // 打开勾稽校验详情
  const openDetail = async () => {
    const realHandSonGridRef = getRealCPASTableRef();
    if (realHandSonGridRef) {
      const verifyData = await realHandSonGridRef.articulationVerifyService.artParseResultList;
      setResultListData({
        verifyResult: verifyData,
        isBackAll: false,
      });
    } else {
      notify(`获取verifyData失败！`, 'error', 2000);
    }
    setOpenDetails(true);
    //realHandSonGridRef.articulationVerifyService.clearArtVerifyMark()
  };

  // 关闭勾稽校验详情
  const closeDetail = () => {
    setOpenDetails(!openDetails);
  };

  const batchExport = async (isTemp: boolean) => {
    const res = await exportExcel(isTemp);
    if (res.type === '导出') {
      if (res.ok) {
        notify(`导出成功！`, 'success', 2000);
      } else {
        PopupComponentsRef.current.show({
          title: '提示信息',
          content: res.msg,
          cancelText: '取消',
          okText: '确定',
          okCallback: () => {
            PopupComponentsRef.current.closeDia();
          },
        });
      }
    }
  };

  const getHeaderData = async (curtid: string) => {
    console.log(curtid, '@@@');
    if (!curtid) return;
    if (origin === '审定财务') {
      let tempHeader: any = {};
      let tempAlias: any = {};
      const resAlias = await getCpasByCategory({
        dbname,
        tid: [curtid],
        category: 'aliasName',
      });
      if (resAlias.data.length) {
        tempAlias = JSON.parse(resAlias.data[0].describe);
        setTitleCenterText(tempAlias?.headerTitleText ?? '');
      } else {
        setTitleCenterText('');
      }
      const resHeader = await getCpasByCategory({
        dbname,
        tid: [curtid],
        category: 'fsHeader',
      });
      if (resHeader.data.length) {
        tempHeader = JSON.parse(resHeader.data[0].describe);
        if (tempHeader?.hasOwnProperty('headerTitleLeftText')) {
          const leftText = tempHeader.headerTitleLeftText
            ? `${tempHeader.headerTitleLeftText}${bsdw}`
            : ' ';
          setTitleLeftText(leftText);
        }

        if (tempHeader?.hasOwnProperty('headerTitleRightText')) {
          setTitleRightText(tempHeader?.headerTitleRightText ?? ' ');
        } else {
          if (tempHeader) {
            setTitleRightText(tempHeader);
            setTitleLeftText(`编制单位: ${bsdw}`);
          } else {
            setTitleRightText(' ');
            setTitleLeftText(' ');
          }
        }
      } else {
        setTitleLeftText(' ');
        setTitleRightText(' ');
      }
    }
  };

  const useEffectFun = async () => {
    const resYear = await fetchTablePeriodList();
    if (resYear.success) {
      if (tableName) {
        const res = await loadTableByServerData(tableName);
      console.log('bbb222')
        if (res?.success) {
          await loadRowsMapData();
          await loadColumnsMapData();
          changeIsInitBtn();
          await getHeaderData(cpasTableTid.current);
        }
      }
    }
  };

  const devSavedRowData = (e: any) => {
    if (e.changes.length) {
      const { key, data } = e.changes[0];
      setPopupDevData((oldData: any) => {
        const newData = [...oldData];
        newData.forEach((item: any) => {
          if (item.signID === key) {
            item.signName = data.signName;
          }
          return item;
        });
        return newData;
      });
    }
  };

  useEffect(() => {
    if (!isInitBtn) {
      useEffectFun();
    }
  }, []);

  useImperativeHandle(ref, () => ({
    CPASInit2: async (rundata: string, isBatch: boolean) => {
      const resYear = await fetchTablePeriodList();
      if (resYear.success) {
        await loadTableByServerData(rundata);
      console.log('ccc333')
        await getHeaderData(cpasTableTid.current);
        if (isBatch) {
          await batchVerifyRecalFun(false, rundata);
        }
      }
    },
    clearDesignTableName: async (tempTableName: any) => {
      const realHandSonGridRef = getRealCPASTableRef();
      if (realHandSonGridRef) {
        return await realHandSonGridRef.removeTableByServer(tempTableName, '', 'fs');
      }
    },
    CPASOpenDetail: () => {
      openDetail();
    },
  }));

  // const saveTitleForm = (isAll: boolean = false) => {
  //     devDataRef.current.instance.saveEditData().then(async () => {
  //         let cpasDescData: any = [];
  //         let cpasDescTextData: any = [];
  //         if (isAll) {
  //             const allTidData = await getallTidsList(true);
  //             if (allTidData.resTid.length) {
  //                 cpasDescData = allTidData.resTid.map((item: any) => {
  //                     return {
  //                         tid: item,
  //                         category: "signRow",
  //                         describe: JSON.stringify(popupDevData)
  //                     }
  //                 });
  //                 cpasDescTextData = allTidData.resTid.map((item: any) => {
  //                     return {
  //                         tid: item,
  //                         category: "fsHeader",
  //                         describe: JSON.stringify(formAllData.pupupTitleText)
  //                     }
  //                 });
  //             } else {
  //                 notify(`签字行内容修改失败！`, "error", 2000);
  //                 setVisiblePopup(false);
  //                 return;
  //             }
  //         } else {
  //             cpasDescData = [{
  //                 tid: cpasTableTid.current,
  //                 category: "signRow",
  //                 describe: JSON.stringify(popupDevData)
  //             }];
  //             cpasDescTextData = [{
  //                 tid: cpasTableTid.current,
  //                 category: "fsHeader",
  //                 describe: JSON.stringify(formAllData.pupupTitleText)
  //             }]
  //         }
  //         console.log(cpasDescData, cpasDescTextData, '@@@');
  //         const tempCpasDesc = {
  //             dbname,
  //             cpasDesc: cpasDescData
  //         }
  //         const tempCpasDescText = {
  //             dbname,
  //             cpasDesc: cpasDescTextData
  //         }
  //         await saveCpasDescList(tempCpasDescText);
  //         const res = await saveCpasDescList(tempCpasDesc);
  //         if (res.success) {
  //             notify(`签字行内容修改成功！`, "success", 2000);
  //             setVisiblePopup(false);
  //         } else {
  //             notify(`签字行内容修改失败！`, "error", 2000);
  //         }

  //     });
  // };

  /**
   * 批量清空数据
   */
  const batchClearFun = async () => {
    setSpinLoad(true);
    setLoadingContent('正在批量清空数据...');
    const allTidData = await getallTidsList(true);
    if (allTidData.resTid.length) {
      const res: any = await batchClearData({
        dbname,
        data_id: '',
        tids: allTidData.resTid,
        cpasTableType: 'fs',
      });
      if (res.success) {
        if (res.data.errorTotal === 0) {
          notify('批量清空数据,成功！', 'success', 2000);
        } else {
          const reName = res.data.processError.map((item: any) => item.name).join(';');
          notify(`【${reName}】，清空数据失败。`, 'warning', 4000);
        }
        await antTabsTabPaneDetail2();
        await loadTableByServerData(tableName);
      console.log('ddd444')
      } else {
        notify('批量清空数据,失败！', 'error', 4000);
      }
      setSpinLoad(false);
      setLoadingContent(' ');
    }
    setSpinLoad(false);
    setLoadingContent(' ');
  };

  /**
   * 批量清空数据
   */
  const batchClearGSFun = async () => {
    setSpinLoad(true);
    setLoadingContent('正在批量清空公式...');
    const allTidData = await getallTidsList(true);
    if (allTidData.resTid.length) {
      const res: any = await batchClearGSData({
        dbname,
        data_id: '',
        tids: allTidData.resTid,
        cpasTableType: 'fs',
      });
      if (res.success) {
        if (res.data.errorTotal === 0) {
          notify('批量清空公式,成功！', 'success', 2000);
        } else {
          const reName = res.data.processError.map((item: any) => item.name).join(';');
          notify(`【${reName}】，清空数据公式。`, 'warning', 4000);
        }
        await antTabsTabPaneDetail2();
        await loadTableByServerData(tableName);
      console.log('eee555')
      } else {
        notify('批量清空公式,失败！', 'error', 4000);
      }
      setSpinLoad(false);
      setLoadingContent(' ');
    }
    setSpinLoad(false);
    setLoadingContent(' ');
  };

  // 校验结果刷新
  const loadTableByServerDataVerifyByRMap = async (paramsObj: {
    serverName: string;
    curTid: string;
  }) => {

    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      try {

        // 重新拿一下
        const verifyData = await realrealHandSonGridRefRef.loadVerifyByServer(paramsObj.curTid);
        const fsParams = {
          dbname,
          tid: paramsObj.curTid,
          type: 'fs',
        };
        const lodaTableZl = await queryVerifyStatefs(fsParams);
        if (lodaTableZl.code === 200) {
          realrealHandSonGridRefRef.setVerifyData(verifyData);
          setResultListData({
            verifyResult: verifyData.artParseResultList,
            isBackAll: false,
          });
        }
        await changeCrticulationVerify(realrealHandSonGridRefRef);
        await antTabsTabPaneDetail2();
        setSpinLoad(false);
        setLoadingContent(' ');
        notify(`获取该表校验结果成功！`, 'success', 2000);
      } catch (error) {
        notify(`获取该表校验结果失败:【${paramsObj.serverName}】！`, 'warning', 2000);
        setSpinLoad(false);
        setLoadingContent(' ');
      }
    }
  };
  return (
    <div className="commonCpasTableBox">
      {/* {spinLoad && <SpinLoading loadString="" />} */}
      <PageLoading isOpen={spinLoad} isMaskClose={false} content={loadingContent} width={200} />
      {/* <FormsTitle formsTitleYear={showYaerData} ></FormsTitle> */}
      <div className="btnsTools">
        {/* <Button
          className="defaultBtnWhite purpleBtnUI"
          onClick={() => {
            setSpinLoad(true);
            setLoadingContent('正在获取校验结果...');
            setTimeout(() => {
              loadTableByServerDataVerifyByRMap({
                serverName: tableName,
                curTid: cpasTableTid.current,
              });
            }, 200);
          }}
          text="校验结果刷新"
        /> */}
        <Button
          type="default"
          className="defaultBtn"
          onClick={async () => {
            setSpinLoad(true);
            setLoadingContent('正在保存数据...');
            const resSave = await saveToServer();
            if (resSave || !resSave) {
              setTimeout(() => {
                setSpinLoad(false);
                setLoadingContent(' ');
              }, 500);
            }
          }}
          text="保存"
        />
        {/* <Button
          className="defaultBtnWhite purpleBtnUI"
          onClick={() => {
            setShowMenuToolBar(!showMenuToolBar);
          }}
          text="模板设计"
        /> */}

        {/* <Button
                className="defaultBtnWhite purpleBtnUI"
                onClick={() => {
                    cpasTableReloadBatch(false);
                }} text='批量刷新'
            /> */}

        {/* <Button
                className="defaultBtnWhite"
                onClick={() => {
                    openDetail();
                }} text='校验详情'
            /> */}

        {/* <Button
                className="defaultBtnWhite"
                disabled={exportExcelBtn}
                onClick={async () => {
                    setExportExcelBtn(true);
                    const res = await exportExcel();
                    if (res.type === '导出') {
                        if (res.ok) {
                            notify(`导出成功！`, "success", 2000);
                        } else {
                            notify(`导出失败！`, "error", 2000);
                        }
                    }
                    setExportExcelBtn(false);

                }} text='批量导出'
            /> */}
        {/* <DropDownButton
                text='文件'
                style={{ height: "30px", marginRight: "8px" }}
                dropDownOptions={{
                    width: 120
                }}
                onItemClick={(e: any) => {
                    if (e.itemData.template === 'items[1].template') {
                        exportChange();
                    }
                }}
            >
                <ButtonItem
                    render={() => (<Upload
                        name={"file"}
                        maxCount={1}
                        beforeUpload={(info) => {
                            importChange(info, cpasTableFsRef.current);
                            return false;
                        }}
                        showUploadList={false}
                        accept=".xlsx"
                    >
                        <div style={{ width: "110px" }}>
                            导入
                        </div>
                    </Upload>)}
                />
                <ButtonItem
                    render={() => (<>导出</>)}
                />
            </DropDownButton> */}
        {/* <DropDownButton
          style={{ height: '30px', margin: '0px 8px 0 4px' }}
          text="批量"
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '批量勾稽重算') {
              batchVerifyRecalFun(false);
            } else if (e.itemData === '批量清空数据') {
              batchClearFun();
            } else if (e.itemData === '批量刷新') {
              cpasTableReloadBatch(false);
            } else {
              batchClearGSFun();
            }
          }}
          items={['批量勾稽重算', '批量清空数据', '批量刷新', '批量清空公式']}
        /> */}
        <DropDownButton
          style={{ height: '30px', margin: '0px 8px 0 4px' }}
          text={origin === '审定财务' ? '导出' : '导出导入'}
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '批量导出模板') {
              console.log('批量导出模版');
              return await exportExcelRef.current.openExportFinanceReportDialog('未审财务', true);
            } else if (e.itemData === '批量导入报表') {
              return await importExcelRef.current.openImportDialog('未审财务');
            } else if (e.itemData === '批量导出报表' || e.itemData === '单个导出报表') {
              batchExport(e.itemData === '批量导出报表');
            } else if (e.itemData === '导出设置') {
              // setVisibleSetting(true);
              refSettingFormPupop.current.showPupop(
                {
                  capsTid: cpasTableTid.current,
                  capsOrigin: origin,
                  capsTabName: CPASTableTabName,
                  capsTitleName: titleCenterText,
                  capsTitleDate: titleYearStr,
                },
                {
                  okCallback: async () => {
                    // setVisibleSetting(false);
                    await getHeaderData(cpasTableTid.current);
                  },
                  cancelCallback: () => {
                    // setVisibleSetting(false);
                  },
                },
              );
            }
          }}
          //   else if (e.itemData === '导出设置(合并)') {
          //     // setVisibleSettingHB(true);
          //     refSettingFormPupopHB.current.showPupop(
          //       {
          //         capsTid: cpasTableTid.current,
          //         capsOrigin: origin,
          //         capsTabName: CPASTableTabName,
          //         capsTitleName: titleCenterText,
          //         capsTitleDate: titleYearStr,
          //       },
          //       {
          //         okCallback: async () => {
          //           // setVisibleSettingHB(false);
          //           await getHeaderData(cpasTableTid.current);
          //         },
          //         cancelCallback: () => {
          //           // setVisibleSettingHB(false);
          //         },
          //       },
          //     );
          //   }
          // }, '导出设置(合并)'
          items={
            origin === '审定财务'
              ? ['单个导出报表', '批量导出报表', '导出设置']
              : ['单个导出报表', '批量导出报表', '导出设置', '批量导出模板', '批量导入报表']
          }
        />

        {/* <DropDownButton
          style={{ height: '30px', marginRight: '4px' }}
          text="模板"
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '切换模板') {
              const data = await getSeekAuditReportTemplate({ zcbfid });
              console.log('当前模板：', data.data.AuditReportTemplate);
              const templateName = data.data.AuditReportTemplate;
              changeTemplatePopupRef.current.showTemplate({ templateName });
            } else {
              saveTemplatePopupRef.current.showTemplate();
            }
          }}
          items={['切换模板', '保存模板']}
        /> */}
        <div className="boxRight" />
        <Button
          className="defaultReloadBtnWhite"
          render={() => <CpasIcon type="icon-refresh" fontSize={16} />}
          onClick={() => {
            if (openDetails) {
              setOpenDetails(!openDetails);
            }
            const realHandSonGridRef = getRealCPASTableRef();
            if (realHandSonGridRef) {
              const dataGrid = realHandSonGridRef.getCpasTableGrid();
              console.log('数据@@@', dataGrid, serverDataLen);
              if (dataGrid.data.length !== serverDataLen) {
                cpasTableChangePupopRef.current.show();
              } else {
                cpasTableReloadBatch(true);
              }
            }
          }}
        />
      </div>
      <div className={`commonCpasTable ${commonCpasTableDisplay}  ${commonCpasTableNot} `}>
        <CpasTableFs
          tabGroup="fs-tab"
          tabLevel={2}
          ieType="json,draft"
          numberZeroReplace={cpasTableZeroReplace}
          type={'fs'}
          name={tableName}
          mapRowsList={rowsMapList}
          mapColumnsList={columnsMapList}
          isShowMenuToolBar={showMenuToolBar}
          verifyMode={true}
          notes={{ tid: cpasTid }}
          // gridData={copyServerData}
          tableDate={titleYearStr}
          tableTitle={titleCenterText}
          tableRiDesc={titleRightText}
          tableLfDesc={titleLeftText}
          isTest={true}
          ref={cpasTableFsRef}
          draftSheetName={titleName}
          afterOnArtCellClick={(a, arr, cb) => {
            const realrealHandSonGridRefRef = getRealCPASTableRef();
            if (realrealHandSonGridRefRef) {
              const p: any = [];
              const resultList =
                realrealHandSonGridRefRef.articulationVerifyService.artParseResultList;
              console.log(resultList);
              if (cb !== null && cb[0]) {
                resultList.forEach((item: any) => {
                  const havePro = item.beVerifiedCoordsMap;
                  console.log(
                    '是否存在该属性',
                    havePro?.hasOwnProperty(cb[0].currentFormula),
                    havePro,
                    cb[0].currentFormula,
                  );

                  if (havePro?.hasOwnProperty(cb[0].currentFormula)) {
                    p.push(item);
                  }
                });
                console.log(p, '@@@ 是否存在该属性 被校验项');
                setResultListData({
                  verifyResult: p,
                  isBackAll: true,
                });
                closeDetail();
              } else {
                return notify('非校验项/已校验通过!', 'error', 2000);
              }
            }
          }}
        />
      </div>
      <CpasTableChangePupop ref={cpasTableChangePupopRef} tableSaveAndReload={saveAndReload} />
      <SaveTemplatePopup
        ref={saveTemplatePopupRef}
        okCallback={async (data: any) => {
          console.log(data, '@@@ 保存模板');
          const res: any = await saveTemplateApi({
            dbName: dbname,
            templateName: data,
            type: 'fs',
            tableNames: tableNameGroup,
          });
          if (res.success) {
            notify('保存成功', 'success', 2000);
          } else {
            notify('保存失败', 'error', 2000);
          }
        }}
        cancelCallback={() => {
          console.log('@@@ ， 取消');
        }}
      />
      <Details
        isOpen={openDetails}
        handleOpen={closeDetail}
        params={cpasTableFsRef?.current?.handsonTableFs}
        result={resultListData.verifyResult}
        isBackAll={resultListData.isBackAll}
        onBackAll={() => {
          setResultListData((oldData: any) => {
            const newData = { ...oldData, isBackAll: false };
            return newData;
          });
        }}
      />
      <PopupComponents ref={PopupComponentsRef} />
      <ChangeTemplatePopup
        ref={changeTemplatePopupRef}
        okCallback={async (data: any) => {
          console.log(data, '@@@ 切换模板');
          setSpinLoad(true);
          setLoadingContent('正在切换模板...');
          const resTemp: any = await templateInitApi({
            dbName: dbname,
            templateName: data,
            tableNames: tableNameGroup,
            type: 'fs',
          });
          if (resTemp.success) {
            await batchVerifyRecalFun(false);
            await antTabsTabPaneDetail2();
            await cpasChangeSpinAntTabs(false, tableName);
            notify(`切换模板成功`, 'success', 2000);
            await cpasChangeSpinAntTabs(true, tableName);
          } else {
            notify(`${resTemp.msg}`, 'error', 2000);
          }
          setSpinLoad(false);
          setLoadingContent(' ');
        }}
        cancelCallback={() => {
          console.log('@@@ ， 取消');
        }}
        changeData={{
          cloudTempType: '报告模板',
        }}
      />
      {/* 导出模板的设置弹窗 */}
      <SettingFormPupop ref={refSettingFormPupop} />;
      <SettingFormPupopHB ref={refSettingFormPupopHB} />
      {/* {useMemo(() => {
        if (visibleSetting) {
          return
        }
        return <></>;
      }, [visibleSetting])}

      {useMemo(() => {
        if (visibleSettingHB) {
          return ;
        }
        return <></>;
      }, [visibleSettingHB])} */}
      <CpasModal
        ref={exportExcelRef}
        type="fs"
        zcbfid={zcbfid}
        zcbfName={zcbfName}
        exportSort={['资产表', '负债表', '利润表', '现金流量表', '现金流补充资料表']}
      />
      <ImportExcelModal
        ref={importExcelRef}
        type="fs"
        title="导入Excel报表"
        okCallback={async () => {
          await loadTableByServerData(tableName);
        }}
      />
    </div>
  );
});
export default React.memo(CommonCpasTable);
